#!/bin/bash
# =========================================
# Script: install_docker.sh
# Description: Install Docker CE on CentOS 7 using Alibaba Cloud mirror
# Author: Qwen (Alibaba Cloud)
# Date: 2025-08-22
# =========================================

set -e  # 遇到错误立即退出

echo "🚀 开始安装 Docker CE（使用阿里云镜像源）..."

# Step 1: 安装 yum-utils
echo "📦 正在安装 yum-utils 工具..."
sudo yum install -y yum-utils

# Step 2: 配置阿里云 Docker CE Yum 源
echo "🔧 配置阿里云 Docker CE 镜像源..."
sudo tee /etc/yum.repos.d/docker-ce.repo <<-'EOF'
[docker-ce]
name=Docker CE
baseurl=https://mirrors.aliyun.com/docker-ce/linux/centos/7/x86_64/stable/
enabled=1
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/docker-ce/linux/centos/gpg
EOF

# Step 3: 清理并重建缓存
echo "🔄 清理 YUM 缓存并生成新缓存..."
sudo yum clean all
sudo yum makecache

# Step 4: 安装 Docker CE
echo "🐳 正在安装 Docker CE..."
sudo yum install -y docker-ce docker-ce-cli containerd.io

# Step 5: 启动并设置开机自启
echo "⚙️ 启动 Docker 服务并设置开机自启..."
sudo systemctl start docker
sudo systemctl enable docker

# Step 6: 配置阿里云镜像加速器
echo "⚡ 配置阿里云镜像加速器: https://esqqmhxy.mirror.aliyuncs.com"
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://esqqmhxy.mirror.aliyuncs.com"]
}
EOF

# Step 7: 重启 Docker 使配置生效
echo "🔄 重启 Docker 服务以应用镜像加速器配置..."
sudo systemctl restart docker

# 验证安装
echo "✅ 验证安装结果..."
docker --version

# 可选：查看镜像加速器是否生效
echo "🔍 当前 Docker 信息（检查镜像加速器是否生效）..."
docker info | grep -A 2 "Registry Mirrors"

echo "🎉 Docker 安装完成，且已配置阿里云镜像加速器！"